<template>
  <div class="contest-create-container">
    <div class="page-header">
      <h2>创建竞赛</h2>
      <el-button @click="goBack" plain round>
        <el-icon><ArrowLeft /></el-icon>
        返回竞赛列表
      </el-button>
    </div>

    <el-card class="create-form-card" shadow="hover">
      <el-form
        ref="contestFormRef"
        :model="contestForm"
        :rules="contestRules"
        label-position="top"
        status-icon
      >
        <!-- 基本信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <div class="title-icon">
              <el-icon><Document /></el-icon>
            </div>
            <h3>基本信息</h3>
          </div>

          <el-form-item label="竞赛标题" prop="title">
            <el-input 
              v-model="contestForm.title" 
              placeholder="请输入竞赛标题" 
              maxlength="100" 
              show-word-limit
              :prefix-icon="Edit"
            />
          </el-form-item>

          <el-form-item label="竞赛描述" prop="description">
            <el-input 
              v-model="contestForm.description" 
              type="textarea" 
              placeholder="请输入竞赛描述" 
              maxlength="2000" 
              show-word-limit
              rows="5"
            />
          </el-form-item>

          <el-form-item label="封面图片" prop="coverImage">
            <el-upload
              class="cover-uploader"
              action="#"
              :http-request="handleCoverUpload"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
            >
              <el-image 
                v-if="contestForm.coverImage" 
                :src="contestForm.coverImage" 
                class="cover-preview"
                fit="cover"
              />
              <div v-else class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <span>上传封面图片</span>
              </div>
            </el-upload>
            <div class="upload-tip">建议尺寸: 1920 x 1080 像素，最大 2MB，支持 jpg、png 格式</div>
            <div v-if="contestForm.coverImage" class="mt-2">
              <el-button type="danger" size="small" @click="removeCoverImage">
                <el-icon><Delete /></el-icon>
                删除图片
              </el-button>
            </div>
          </el-form-item>
        </div>

        <!-- 时间设置区域 -->
        <div class="form-section">
          <div class="section-title">
            <div class="title-icon">
              <el-icon><Calendar /></el-icon>
            </div>
            <h3>时间设置</h3>
          </div>

          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="contestForm.startTime"
                  type="datetime"
                  placeholder="选择开始时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabledDate="disablePastDates"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="contestForm.endTime"
                  type="datetime"
                  placeholder="选择结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabledDate="disablePastDates"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 参与设置区域 -->
        <div class="form-section">
          <div class="section-title">
            <div class="title-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <h3>参与设置</h3>
          </div>

          <el-form-item label="参与人数限制" prop="participantLimit">
            <el-input-number
              v-model="contestForm.participantLimit"
              :min="0"
              :max="10000"
              placeholder="0表示不限制人数"
              style="width: 220px"
            />
            <span class="limit-tip">注: 0表示不限制人数</span>
          </el-form-item>

          <el-form-item label="证书设置">
            <div class="certificate-setting">
              <el-switch
                v-model="contestForm.certificateEnabled"
                active-text="启用证书"
                inactive-text="不启用证书"
              />
                
              <div class="certificate-count" v-if="contestForm.certificateEnabled">
                <span>颁发给前</span>
                <el-input-number
                  v-model="contestForm.certificateCount"
                  :min="1"
                  :max="100"
                  size="small"
                  controls-position="right"
                />
                <span>名选手</span>
              </div>
            </div>
          </el-form-item>
        </div>

        <!-- 提交按钮区域 -->
        <div class="form-actions">
          <el-button type="primary" round :loading="submitting" @click="submitForm">
            <el-icon><Check /></el-icon>
            提交竞赛
          </el-button>
          <el-button round @click="resetForm">
            <el-icon><Refresh /></el-icon>
            重置表单
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Document, 
  Edit, 
  Calendar, 
  UserFilled, 
  Check, 
  Refresh, 
  Plus,
  Delete
} from '@element-plus/icons-vue'
import { createContest } from '@/api/contest'
import { uploadContestCover } from '@/api/file'
import { getUserInfo } from '@/api/user'
import { RESOURCE_BASE_URL } from '@/config'

const router = useRouter()
const contestFormRef = ref(null)
const submitting = ref(false)
const currentUser = ref(null)

// 竞赛表单数据
const contestForm = reactive({
  title: '',
  description: '',
  coverImage: '',
  startTime: '',
  endTime: '',
  participantLimit: 0,
  certificateEnabled: false,
  certificateCount: 3
})

// 表单验证规则
const contestRules = {
  title: [
    { required: true, message: '请输入竞赛标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入竞赛描述', trigger: 'blur' },
    { max: 2000, message: '描述最多2000个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && contestForm.startTime && new Date(value) <= new Date(contestForm.startTime)) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  participantLimit: [
    { type: 'number', message: '参与人数限制必须为数字', trigger: 'blur' }
  ],
  certificateCount: [
    { required: true, message: '请输入证书数量', trigger: 'blur' }
  ]
}

// 禁用过去的日期
const disablePastDates = (date) => {
  return date < new Date(new Date().toDateString())
}

// 图片上传前验证
const beforeCoverUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传封面只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传封面图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

// 处理封面上传
const handleCoverUpload = async (options) => {
  const { file } = options
  
  // 验证文件是否符合要求
  const isValid = beforeCoverUpload(file)
  if (!isValid) return
  
  try {
    // 调用封面上传API
    const res = await uploadContestCover(file)
    if (res.code === 200 && res.data) {
      // 设置封面图片URL
      const url = res.data.url
      // 如果URL是以/开头的相对路径，添加正确的基础URL
      if (url.startsWith('/')) {
        contestForm.coverImage = `${RESOURCE_BASE_URL}${url}`
      } else {
        contestForm.coverImage = url
      }
      ElMessage.success('封面上传成功')
    } else {
      ElMessage.error(res.message || '封面上传失败')
    }
  } catch (error) {
    console.error('封面上传失败', error)
    ElMessage.error('封面上传失败，请稍后重试')
  }
}

// 删除封面图片
const removeCoverImage = () => {
  ElMessageBox.confirm(
    '确定要删除当前封面图片吗？',
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    contestForm.coverImage = ''
    ElMessage.success('封面已删除')
  }).catch(() => {
    // 取消删除
  })
}

// 获取当前用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200) {
      currentUser.value = res.data
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    ElMessage.warning('无法获取用户信息，请刷新页面重试')
  }
}

// 在组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})

// 添加日期格式化工具函数
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  
  // 确保日期字符串格式正确
  try {
    // 解析日期字符串，不创建Date对象，避免时区转换问题
    return dateString;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateString;
  }
}

// 提交表单
const submitForm = async () => {
  if (!contestFormRef.value) return
  
  await contestFormRef.value.validate(async (valid) => {
    if (valid) {
      // 检查用户信息是否已获取
      if (!currentUser.value || !currentUser.value.id) {
        ElMessage.warning('无法获取用户信息，请刷新页面重试')
        return
      }

      ElMessageBox.confirm(
        '确定要提交此竞赛吗？提交后需等待管理员审核',
        '提交确认',
        {
          confirmButtonText: '确定提交',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(async () => {
        submitting.value = true
        try {
          // 直接使用字符串形式的时间，避免时区转换问题
          const submitData = {
            ...contestForm,
            creatorId: currentUser.value.id, // 添加创建者ID
            startTime: formatDateTime(contestForm.startTime),
            endTime: formatDateTime(contestForm.endTime)
          }
          
          console.log('提交竞赛数据:', submitData);
          console.log('原始开始时间:', contestForm.startTime);
          console.log('原始结束时间:', contestForm.endTime);
          
          await createContest(submitData)
          ElMessage.success('竞赛创建成功，等待管理员审核')
          
          // 跳转到竞赛列表页
          setTimeout(() => {
            router.push('/contest/list')
          }, 1500)
        } catch (error) {
          console.error('创建竞赛失败', error)
          ElMessage.error('创建竞赛失败，请稍后重试')
        } finally {
          submitting.value = false
        }
      }).catch(() => {
        // 取消提交
      })
    } else {
      ElMessage.warning('请正确填写表单信息')
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!contestFormRef.value) return
  
  ElMessageBox.confirm(
    '确定要重置表单吗？所有已填写的内容将被清空',
    '重置确认',
    {
      confirmButtonText: '确定重置',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    contestFormRef.value.resetFields()
    contestForm.coverImage = ''
    ElMessage.success('表单已重置')
  }).catch(() => {
    // 取消重置
  })
}

// 返回竞赛列表
const goBack = () => {
  router.push('/contest/list')
}
</script>

<style lang="scss" scoped>
.contest-create-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
      font-size: 24px;
      font-weight: 600;
    }
  }
  
  .create-form-card {
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
    
    .form-section {
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px dashed #ebeef5;
      
      &:last-child {
        border-bottom: none;
        margin-bottom: 0;
      }
      
      .section-title {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        
        .title-icon {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background-color: #ecf5ff;
          color: #409eff;
          margin-right: 10px;
          font-size: 18px;
        }
        
        h3 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: #303133;
        }
      }
    }
    
    .cover-uploader {
      display: flex;
      flex-direction: column;
      
      .cover-preview {
        width: 100%;
        max-width: 500px;
        height: 280px;
        border-radius: 8px;
        object-fit: cover;
      }
      
      .upload-placeholder {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 100%;
        max-width: 500px;
        height: 280px;
        border: 1px dashed #d9d9d9;
        border-radius: 8px;
        cursor: pointer;
        transition: border-color 0.3s;
        
        &:hover {
          border-color: #409eff;
        }
        
        .el-icon {
          font-size: 30px;
          color: #8c8c8c;
          margin-bottom: 10px;
        }
        
        span {
          color: #8c8c8c;
          font-size: 14px;
        }
      }
      
      .upload-tip {
        font-size: 12px;
        color: #909399;
        margin-top: 10px;
      }
    }
    
    .limit-tip {
      margin-left: 10px;
      font-size: 13px;
      color: #909399;
    }
    
    .certificate-setting {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 20px;
      
      .certificate-count {
        display: flex;
        align-items: center;
        gap: 10px;
        
        span {
          color: #606266;
        }
        
        .el-input-number {
          width: 110px;
        }
      }
    }
    
    .form-actions {
      display: flex;
      justify-content: center;
      gap: 20px;
      margin-top: 30px;
      
      .el-button {
        min-width: 120px;
        
        .el-icon {
          margin-right: 5px;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .contest-create-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }
    
    .certificate-setting {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
    }
  }
}
</style> 